package org.thirdeyetvg.ncanreader;

import org.thirdeyetvg.ncanreader.activity.accessible.EpubAccessibileReaderActivity;
import org.thirdeyetvg.ncanreader.activity.accessible.TextAccessibileReaderActivity;
import org.thirdeyetvg.ncanreader.activity.normal.EpubNormalReaderActivity;
import org.thirdeyetvg.ncanreader.activity.normal.TextNormalReaderActivity;
import org.thirdeyetvg.ncanreader.constants.ApplicationConstants;
import org.thirdeyetvg.ncanreader.constants.ApplicationConstants.ResultSource;
import org.thirdeyetvg.ncanreader.constants.ApplicationConstants.SupportedFileTypes;
import org.thirdeyetvg.ncanreader.constants.ApplicationConstants.SupportedModes;
import org.thirdeyetvg.ncanreader.helper.LoggerUtil;

import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

/**
 * This is the first activity to load
 * 
 */
public class InitialActivity extends Activity {
	private static final String CLASS_NAME = InitialActivity.class.getName();
	private static final LoggerUtil logger = new LoggerUtil(CLASS_NAME);

	private String fileName = "";
	private SupportedModes mode = null;
	private SupportedFileTypes fileType = null;
	// This is to remember the previously selected path
	private static String path = Environment.getExternalStorageDirectory()
			.getPath();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_initial);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_initial, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		switch (item.getItemId()) {
		case R.id.menu_browse_file:
			showFileBrowser();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}

	}

	private void showFileBrowser() {
		Intent browseFile = new Intent(InitialActivity.this,
				FileBrowserActivity.class);
		browseFile.putExtra("path", path);
		startActivityForResult(browseFile, 0);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		String methodName = "onActivityResult";
		logger.entering(methodName);
		try {
			if (resultCode == RESULT_OK) {
				Bundle extras = data.getExtras();
				ResultSource result = ResultSource.unknown;
				if (extras != null
						&& extras.containsKey(ApplicationConstants.RESULT)) {
					logger.debug("RESULT:"
							+ extras.getString(ApplicationConstants.RESULT));
					result = ResultSource.valueOf(extras
							.getString(ApplicationConstants.RESULT));
				}
				switch (result) {
				case file_selection:
					handleSelectedFile(extras.getString("data"));
					break;
				case mode_selection:
					mode = SupportedModes.valueOf(extras.getString("data"));
					readOpenedFile();
					break;
				}
				// TODO Need to look into this
				// super.onActivityResult(requestCode, resultCode, data);
			}
		} catch (Exception e) {
			logger.error("Exception in onActivityResult:" + e.toString());
		}
	}

	private void readOpenedFile() {
		if (fileType != null) {
			Intent readFile;
			switch (mode) {
			case accessible:
				readFile = getAccessibleTextEpubIntent();
				readFile.putExtra("fileName", fileName);
				startActivityForResult(readFile, 0);
				break;
			case normal:
				readFile = getNormalTextEpubIntent();
				readFile.putExtra("fileName", fileName);
				startActivityForResult(readFile, 0);
				break;
			default:
				break;
			}
		}
	}

	private Intent getAccessibleTextEpubIntent() {
		@SuppressWarnings("rawtypes")
		Class activityClass = null;
		switch (fileType) {
		case epub:
			activityClass = EpubAccessibileReaderActivity.class;
			break;
		case txt:
			activityClass = TextAccessibileReaderActivity.class;
			break;

		default:
			break;
		}
		return new Intent(InitialActivity.this, activityClass);
	}

	private Intent getNormalTextEpubIntent() {
		@SuppressWarnings("rawtypes")
		Class activityClass = null;
		switch (fileType) {
		case epub:
			activityClass = EpubNormalReaderActivity.class;
			break;
		case txt:
			activityClass = TextNormalReaderActivity.class;
			break;

		default:
			break;
		}
		return new Intent(InitialActivity.this, activityClass);
	}

	// TODO Use this method to open recently opened files
	private void handleSelectedFile(String selectedFileName) {
		this.fileName = selectedFileName;
		path = fileName.substring(0,
				fileName.lastIndexOf('/', fileName.length()) + 1);
		String fileExtension = fileName.substring(
				fileName.lastIndexOf('.') + 1, fileName.length());
		logger.debug("File Extension:" + fileExtension);
		if (fileExtension.equalsIgnoreCase(SupportedFileTypes.txt.toString())) {
			Toast.makeText(getApplicationContext(), "Text file opened",
					Toast.LENGTH_LONG).show();
			fileType = SupportedFileTypes.txt;
		} else if (fileExtension.equalsIgnoreCase(SupportedFileTypes.epub
				.toString())) {
			Toast.makeText(getApplicationContext(), "Epub file opened",
					Toast.LENGTH_LONG).show();
			fileType = SupportedFileTypes.epub;
		} else {
			Toast.makeText(getApplicationContext(), "Invalid file format",
					Toast.LENGTH_LONG).show();
			fileType = null;
		}
		if (fileType != null) {
			// TODO Check preference calling
			// After opening the file show the mode selection activity
			showModeSelection();
		}
	}

	private void showModeSelection() {
		Intent selectMode = new Intent(InitialActivity.this,
				ModeSelectionActivity.class);
		startActivityForResult(selectMode, 0);

	}
}
